package com.mdp.im.core.socket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.UnknownHostException;

/**
 * WebSocket Server
 * 
 * @author chenyc
 * @date 2018/4/3
 */
@Service
public class WebSocketServer {
    
    private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
    
    @Autowired
    WebSocketChannelInitializer webSocketChannelInitializer;


    /**
     * 监听端口号
     */
    @Value("${mdp.im.port:3333}")
    private Integer port=3333;
    
    /**
     * Boss线程数
     */
    private int bossThreads = 1;
    
    /**
     * Worker线程数
     */
    private int workerThreads = 0;
    
    
    public int getBossThreads() {
        return this.bossThreads;
    }
    public void setBossThreads(int bossThreads) {
        this.bossThreads = bossThreads;
    }
    
    public int getWorkerThreads() {
        return this.workerThreads;
    }
    public void setWorkerThreads(int workerThreads) {
        this.workerThreads = workerThreads;
    }
    /**
     * 启动服务
     * @throws InterruptedException 
     */
    
    public void start() throws InterruptedException, UnknownHostException {

        // BossGroup处理nio的Accept事件（TCP连接）
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(this.bossThreads);
        // Worker处理nio的Read和Write事件（通道的I/O事件）
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(this.workerThreads);
        
        try {
            // handler在初始化时就会执行，而childHandler会在客户端成功connect后才执行。
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 128)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .handler(new LoggingHandler(LogLevel.DEBUG))
            .childHandler(webSocketChannelInitializer);
            
            ChannelFuture f = bootstrap.bind(port).sync();
            logger.info("The netty websocket server is now ready to accept requests on port {}", this.port);


            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
    
    /**
     * 初始化Netty ChannelGroup
     */
//    private void initChannelGroup() {
//        // 得到所有群组类型的channel
//        Map<String, Object> parameters = new HashMap<>(1);
//        parameters.put("deleteAt", 0);
//        ChannelService serviceProxy = ServiceProxy.newProxyInstance(ServiceFactory.createChannelService());
//        List<ChannelListDTO> dtoList = serviceProxy.listGroupChannel(parameters, 0);
//        for(ChannelListDTO dto : dtoList) {
//            ChannelsHolder.getChannelGroups().put(dto.getId(), new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE));
//        }
//        ChannelsHolder.getChannelGroups().put("all", new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE));
//    }

}
